/**
 * 
 */
package com.trungkent.smsbackup.adapter;

import java.util.List;

import com.trungkent.smsbackup.R;
import com.trungkent.smsbackup.model.Person;
import com.trungkent.smsbackup.util.LoadImageFromContact;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author setamember
 * 
 */
public class SMSAdapter extends BaseAdapter {

	private Context mContext;

	private List<Person> mPersonList;

	private LoadImageFromContact mLoadImageFromContact;
	
	public SMSAdapter(Context context, List<Person> personList) {
		mContext = context;
		mPersonList = personList;
		mLoadImageFromContact = new LoadImageFromContact(null);
	}

	@Override
	public int getCount() {
		return mPersonList == null ? 0 : mPersonList.size();
	}

	@Override
	public Object getItem(int position) {
		return mPersonList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;

		if (convertView == null) {
			convertView = ((Activity) mContext).getLayoutInflater().inflate(
					R.layout.item_sms, null);

			holder = new ViewHolder();
			holder.imgAvatar = (ImageView) convertView
					.findViewById(R.id.imgAvatar);
			holder.imgChecker = (ImageView) convertView
					.findViewById(R.id.imgChecker);

			holder.txvContactName = (TextView) convertView
					.findViewById(R.id.txvContactName);
			holder.txvTotalMessage = (TextView) convertView
					.findViewById(R.id.txvTotalMess);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		if(mPersonList.get(position).name == null || "".equalsIgnoreCase(mPersonList.get(position).name)) {
			holder.txvContactName.setText(mPersonList.get(position).address);
		} else {
			holder.txvContactName.setText(mPersonList.get(position).name);
		}
		
		holder.txvTotalMessage.setText("Total SMS: "
				+ mPersonList.get(position).smsList.size());

		if (mPersonList.get(position).isCheck) {
			holder.imgChecker.setImageResource(R.drawable.ic_navigation_accept);
		} else {
			holder.imgChecker.setImageResource(Color.TRANSPARENT);
		}

		if(mPersonList.get(position).photoUri != null) {
			mLoadImageFromContact.loadImage(mPersonList.get(position).photoUri,
					holder.imgAvatar);
		} else {
			holder.imgAvatar.setImageResource(R.drawable.ic_logo);
		}
		
		return convertView;
	}

	static class ViewHolder {
		ImageView imgAvatar;
		ImageView imgChecker;

		TextView txvContactName;
		TextView txvTotalMessage;
	}
}
